<template>
  <!-- 新增活动 -->
  <el-dialog
    v-model="visible"
    :title="sceneId ? '修改场景营销' : '新增场景营销'"
    class="addCoupon"
    width="1100px"
    center
    top="10vh"
    :close-on-click-modal="false"
    @close="close"
  >
    <!-- 新增用户 -->
    <div class="addCouponBox">
      <el-form
        ref="ruleFormRef"
        class="formBox"
        :model="form"
        label-width="150px"
        :rules="rules"
      >
        <el-form-item label="营销类型">
          <el-radio-group v-model="form.sceneType" class="comRadio">
            <el-radio :label="1">节日营销</el-radio>
            <el-radio :label="2">会员日营销</el-radio>
            <el-radio :label="3">生日营销</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="营销名称" prop="sceneName">
          <el-input
            v-model="form.sceneName"
            maxlength="20"
            placeholder="请输入营销名称"
            onblur="value=value.replace(/(^\s*)|(\s*$)/g, '')"
          />
        </el-form-item>
        <el-form-item class="item-time" label="活动时间" prop="sceneTime">
            <el-date-picker
              v-model="dateInfo"
              :disabled="form.timeType === '2'"
              type="datetimerange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          <div v-if="form.sceneType === 2">
            <dl class="dl-month">
              <dt>
                <el-radio
                  v-model="form.sceneTimeType"
                  :label="1"
                >每月</el-radio>
              </dt>
              <dd>
                每月<el-input
                  v-model="formExtra.monthStart"
                  maxlength="9"
                  oninput="value=value.replace(/[^\d]/g,'')"
                />日 至 每月<el-input
                  v-model="formExtra.monthEnd"
                  maxlength="9"
                  oninput="value=value.replace(/[^\d]/g,'')"
                />日
              </dd>
            </dl>
            <dl>
              <dt>
                <el-radio
                  v-model="form.sceneTimeType"
                  :label="2"
                >每周</el-radio>
              </dt>
              <dd>
                <el-checkbox-group v-model="formExtra.weekList">
                  <el-checkbox label="1">周一</el-checkbox>
                  <el-checkbox label="2">周二</el-checkbox>
                  <el-checkbox label="3">周三</el-checkbox>
                  <el-checkbox label="4">周四</el-checkbox>
                  <el-checkbox label="5">周五</el-checkbox>
                  <el-checkbox label="6">周六</el-checkbox>
                  <el-checkbox label="7">周日</el-checkbox>
                </el-checkbox-group>
              </dd>
            </dl>
            <dl>
              <dt>
                <el-radio
                  v-model="form.sceneTimeType"
                  :label="3"
                >每日</el-radio>
              </dt>
              <dd>
                <el-time-picker
                  v-model="formExtra.dayTime"
                  is-range
                  range-separator="-"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  placeholder="选择时间范围"
                  value-format="HH:mm:ss"
                />
              </dd>
            </dl>
          </div>
          <div v-if="form.sceneType === 3">
            <el-radio-group v-model="form.sceneTimeType">
              <el-radio :label="4">生日当天</el-radio>
              <el-radio :label="5">生日当周</el-radio>
              <el-radio :label="6">生日当月</el-radio>
            </el-radio-group>
          </div>
        </el-form-item>
        <el-form-item
          class="item-rule"
          label="营销规则"
        >
          <dl>
            <dt>
              <el-radio
                v-model="form.sceneRule"
                :label="1"
              >所有等级会员，同一规则</el-radio>
            </dt>
            <dd>
              <el-table :data="vipSameRuleList" border>
                <el-table-column prop="memberLevelId" label="会员等级">
                  <template #default>
                    <span>全部等级</span>
                  </template>
                </el-table-column>
                <el-table-column prop="ifFreeShipping" label="包邮">
                  <template #default="scope">
                    <el-checkbox
                      v-model="scope.row.ifFreeShipping"
                      :true-label="1"
                      :false-label="0"
                    >包邮</el-checkbox>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="discount"
                  label="折扣"
                  show-overflow-tooltip
                >
                  <template #default="scope">
                    <!-- <el-input v-model="scope.row.discount" type="number" oninput="value=value.replace(/([^\d|\.])/g, '')" /> 折 -->
                    <el-input-number
                      v-model="scope.row.discount"
                      :precision="1"
                      :min="1"
                      :max="9.9"
                    />
                    折
                  </template>
                </el-table-column>
                <el-table-column
                  prop="ids"
                  label="优惠券"
                  show-overflow-tooltip
                >
                  <template #default="scope">
                    <span class="selectBtn" @click="selectCoupons(scope.row)">
                      请选择
                      <i
                        v-if="scope.row.ids && scope.row.ids.length !== 0"
                        class="selectNum"
                      >{{ scope.row.ids.length }}</i>
                    </span>
                  </template>
                </el-table-column>
              </el-table>
            </dd>
          </dl>
          <dl>
            <dt>
              <el-radio
                v-model="form.sceneRule"
                :label="2"
              >不同等级会员，不同规则</el-radio>
            </dt>
            <dd>
              <el-table :data="vipDifferentRuleList" border>
                <el-table-column prop="memberLevelName" label="会员等级" />
                <el-table-column prop="ifFreeShipping" label="包邮">
                  <template #default="scope">
                    <el-checkbox
                      v-model="scope.row.ifFreeShipping"
                      :true-label="1"
                      :false-label="0"
                    >包邮</el-checkbox>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="discount"
                  label="折扣"
                  show-overflow-tooltip
                >
                  <template #default="scope">
                    <!-- <el-input v-model="scope.row.discount" type="number" oninput="value=value.replace(/([^\d|\.])/g, '')" /> 折 -->
                    <el-input-number
                      v-model="scope.row.discount"
                      :precision="1"
                      :min="1"
                      :max="9.9"
                    />
                    折
                  </template>
                </el-table-column>
                <el-table-column
                  prop="ids"
                  label="优惠券"
                  show-overflow-tooltip
                >
                  <template #default="scope">
                    <span class="selectBtn" @click="selectCoupons(scope.row)">
                      请选择
                      <i
                        v-if="scope.row.ids && scope.row.ids.length !== 0"
                        class="selectNum"
                      >{{ scope.row.ids.length }}</i>
                    </span>
                  </template>
                </el-table-column>
              </el-table>
            </dd>
          </dl>
        </el-form-item>
      </el-form>
    </div>
    <span class="dialog-footer">
      <el-button
        type="primary"
        @click="addCouponFn"
      >保 存</el-button>
      <el-button type="danger" @click="goToScene">取 消</el-button>
    </span>
    <!-- 新建分组弹框 -->
    <el-dialog
      v-model="groupVisible"
      title="选择优惠券"
      width="55%"
      top="50px"
      class="group-dialog"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      :modal="false"
    >
      <!-- 表格 -->
      <div class="tableBox">
        <el-table
          ref="multipleTableRef"
          :data="groupData"
          border
          :header-cell-style="{ background: '#EEF3FF', color: '#333333' }"
          tooltip-effect="dark"
          style="width: 100%"
          max-height="600"
          row-key="shopCouponId"
          @selection-change="handleSelectionChange"
        >
          <el-table-column
            type="selection"
            :reserve-selection="true"
            width="55"
          />
          <el-table-column label="优惠券名称" width="220">
            <template #default="scope">
              {{ scope.row.couponName }}
            </template>
          </el-table-column>
          <el-table-column label="类型" show-overflow-tooltip>
            <template #default="scope">
              <span v-if="scope.row.couponType === 1">满减券</span>
              <span v-if="scope.row.couponType === 2">折扣券</span>
            </template>
          </el-table-column>
          <el-table-column label="状态" show-overflow-tooltip>
            <template #default="scope">
              <span v-if="scope.row.state === 0">未开始</span>
              <span v-if="scope.row.state === 1">进行中</span>
              <span v-if="scope.row.state === 2">已结束</span>
            </template>
          </el-table-column>
          <el-table-column prop="content" label="内容" show-overflow-tooltip />
          <el-table-column
            prop="createTime"
            label="创建时间"
            show-overflow-tooltip
          />
        </el-table>
        <div class="fenye">
          <el-pagination
            :current-page="groupPage.page"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="groupPage.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="groupPage.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
      <template #footer>
        <div class="footBtnBox">
          <span class="dialog-footer">
            <el-button type="primary" @click="saveIdList">确 定</el-button>
            <el-button @click="closeSelect">取 消</el-button>
          </span>
        </div>
      </template>
    </el-dialog>
  </el-dialog>
</template>

<script setup>
import { defineComponent, reactive, ref } from 'vue';

import { getShopId } from '@/utils/auth'

import {
  sceneUpate,
  sceneAdd,
  getMemberLevels,
  getCoupon,
  getSceneDetail,
} from '@/api/marketing'

defineComponent({})

const emit = defineEmits(['reset'])

defineExpose({
  open, close
})

function initForm (data) {
  return {
    shopId: data && data.shopId || parseInt(getShopId()) || 0,
    sceneType: data && data.shopId || 1,
    sceneRule: data && data.sceneRule || 1,
    sceneTimeType: data && data.sceneTimeType || 1,
    sceneTime: data && data.sceneTime || null,
    startTime: data && data.startTime || null,
    endTime: data && data.endTime || null,
    members: data && data.members || [],
  }
}
const sceneId = ref(0)
const visible = ref(false)
const groupVisible = ref(false)
const visitDetail = ref(false)
const ruleFormRef = ref();
const form = ref(initForm())
const dateInfo = ref([])
const vipSameRuleList = ref([{}])
const vipDifferentRuleList = ref([])
const groupData = ref([])
const multipleTableRef = ref()
const multipleSelection = ref([])
const currentRow = ref({})
const formExtra = reactive({
  monthStart: '',
  monthEnd: '',
  weekList: [],
  dayTime: ['00:00:00', '23:59:59'],
})

const rules = {
  sceneName: [
    { required: true, message: '请输入营销名称', trigger: 'blur' },
  ],
  sceneTime: [
    { required: true, validator: validDate, trigger: 'change' },
  ]
}
function validDate (rule, value, callback) {
  if (form.sceneType === 3) {
    return callback()
  }
  if (!dateInfo.value || !dateInfo.value.length) {
    return callback(new Error('请选择活动时间'))
  }
  callback()
}

function open (id, isDetail) {
  sceneId.value = id
  visitDetail.value = isDetail
  if (id) {
    vipSameRuleList.value = [
      {
        ifFreeShipping: 0,
        discount: null,
        ids: [],
      },
    ]
    getCouponInfo()
  } else {
    vipSameRuleList.value = [
      {
        // memberLevelId: 0,
        ifFreeShipping: 0,
        discount: null,
        ids: [],
      },
    ]
    getMemberLevelsData()
  }
  visible.value = true
}
function close () {
  visible.value = false
  form.value = initForm()
  dateInfo.value = []
  vipSameRuleList.value = [{}]
  vipDifferentRuleList.value = []
  multipleSelection.value = []
  multipleTableRef.value?.clearSelection()
  ruleFormRef.value?.resetFields()
}

function getCouponInfo () {
  getSceneDetail({
    sceneId: sceneId.value,
    shopId: form.value.shopId,
  }).then(res => {
    form.value = res.data
    dateInfo.value = [form.value.startTime, form.value.endTime]
    switch (form.value.sceneTimeType) {
    case 1:
      formExtra.monthStart = form.value.sceneTime.split('-')[0]
      formExtra.monthEnd = form.value.sceneTime.split('-')[1]
      break
    case 2:
      formExtra.weekList = form.value.sceneTime.split('-').filter((item) => {
        return item !== 0
      })
      break
    default:
      break
    }
    if (form.value.sceneRule === 1) {
      vipSameRuleList.value = form.value.members.splice(0, 1)
      getMemberLevels().then((res) => {
        if (res.code === '') {
          vipDifferentRuleList.value = res.data
        }
      })
    } else {
      vipDifferentRuleList.value = form.value.members
    }
  })
}

// 选择优惠券
function selectCoupons (row) {
  currentRow.value = row
  getCouponList()
  multipleSelection.value = []
  groupVisible.value = true
}

let groupPage = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

function getCouponList () {
  getCoupon(groupPage).then((res) => {
    if (res.code === '') {
      groupPage.total = res.data.total
      groupData.value = res.data.list
      multipleTableRef.value.clearSelection()
      for (let i = 0; i < currentRow.value.ids?.length; i++) {
        groupData.value.forEach((item) => {
          if (item.shopCouponId === currentRow.value.ids[i]) {
            multipleTableRef.value.toggleRowSelection(item, true)
          }
        })
      }
    }
  })
}

function handleSizeChange (val) {
  groupPage.pageSize = val
  getCouponList()
}
function handleCurrentChange (val) {
  groupPage.page = val
  getCouponList()
}

// 选中商品
function handleSelectionChange (val) {
  multipleSelection.value = val
}

// 保存选择商品ID
function saveIdList () {
  const idList = []
  multipleSelection.value.forEach((i) => {
    idList.push(i.shopCouponId)
  })
  var curIndex = 0
  var curItem = ''
  vipDifferentRuleList.value.forEach((item, index) => {
    if (item.memberLevelId === currentRow.value.memberLevelId) {
      curIndex = index
      curItem = item
    }
  })
  if (curItem) {
    curItem.ids = idList
    vipDifferentRuleList.value[curIndex] = curItem
  } else {
    vipSameRuleList.value[0].ids = idList
  }
  groupVisible.value = false
}
// 取消选择
function closeSelect () {
  groupVisible.value = false
}
// 跳转列表
function goToScene () {
  emit('reset')
}

// 查询会员等级数据
function getMemberLevelsData () {
  getMemberLevels().then((res) => {
    if (res.code === '') {
      vipDifferentRuleList.value = res.data
    }
  })
}

function addCouponFn () {
  ruleFormRef.value.validate((valid) => {
    if (valid) {
      switch (form.value.sceneType) {
      // 节日营销
      case 1:
        if (dateInfo.value.length === 0) {
          ElMessage.warning('节日营销时间不能为空！')
          return false
        } else {
          form.value.startTime = dateInfo.value[0]
          form.value.endTime = dateInfo.value[1]
        }
        break
        // 会员日营销
      case 2:
        if (dateInfo.value.length === 0) {
          ElMessage.warning('活动时间不能为空！')
          return false
        } else {
          form.value.startTime = dateInfo.value[0]
          form.value.endTime = dateInfo.value[1]
        }
        if (
          form.value.sceneTimeType !== 1 &&
                form.value.sceneTimeType !== 2 &&
                form.value.sceneTimeType !== 3
        ) {
          ElMessage.warning('请选择营销时间！')
          return false
        }
        switch (form.value.sceneTimeType) {
        // 1-每月 2-每周 3-每日
        case 1:
          if (!formExtra.monthStart) {
            ElMessage.warning('请填写每月多少日开始！')
            return false
          } else if (!formExtra.monthEnd) {
            ElMessage.warning('请填写每月多少日结束！')
            return false
          } else {
            form.value.sceneTime =
            formExtra.monthStart + '-' + formExtra.monthEnd
          }
          break
        case 2:
          if (formExtra.weekList.length === 0) {
            ElMessage.warning('请选择每周多选框！')
            return false
          } else {
            form.value.sceneTime = ''
            for (let i = 1; i < 8; i++) {
              var flag = false
              for (let j = 0; j < formExtra.weekList.length; j++) {
                if (parseInt(formExtra.weekList[j]) === i) {
                  flag = true
                  break
                }
              }
              if (i === 1) {
                form.value.sceneTime = flag ? i : 0
              } else {
                form.value.sceneTime += '-' + (flag ? i : 0)
              }
            }
          }
          break
        case 3:
          if (!formExtra.dayTime || formExtra.dayTime.length === 0) {
            ElMessage.warning('每日时间不能为空！')
            return false
          } else {
            form.value.sceneTime =
            formExtra.dayTime[0] + '-' + formExtra.dayTime[1]
          }
          break
        }
        break
        // 生日营销
      case 3:
        if (
          form.value.sceneTimeType !== 4 &&
                form.value.sceneTimeType !== 5 &&
                form.value.sceneTimeType !== 6
        ) {
          ElMessage.warning('请选择营销时间！')
          return false
        }
        break
      }
      if (form.value.sceneRule === 1) {
        var discountRule = true
        form.value.memberParams = vipSameRuleList.value.map((item) => {
          if (item.discount) {
            item.discount = parseInt(item.discount)
          } else {
            discountRule = false
          }
          return item
        })
        if (!discountRule) {
          ElMessage.warning('折扣不能为空！')
          return false
        }
      } else {
        var discountRule = true
        // var couponRule = true
        form.value.memberParams = vipDifferentRuleList.value.map((item) => {
          const newItem = {
            memberLevelId: item.memberLevelId,
          }
          newItem.ifFreeShipping = item.ifFreeShipping === 1 ? 1 : 0
          if (item.discount) {
            newItem.discount = parseInt(item.discount)
          } else {
            discountRule = false
          }
          if (item.ids && item.ids.length !== 0) {
            newItem.ids = item.ids
          }
          // else {
          //   couponRule = false
          // }
          return newItem
        })

        if (!discountRule) {
          ElMessage.warning('折扣不能为空！')
          return false
        }
      }
      if (sceneId.value) {
        sceneUpate(form.value).then((res) => {
          if (res.code === '') {
            ElMessage.success('修改成功')
            emit('reset')
          } else {
            ElMessage.error(res.message)
          }
        })
      } else {
        sceneAdd(form.value).then((res) => {
          if (res.code === '') {
            ElMessage.success('提交成功')
            emit('reset')
          } else {
            ElMessage.error(res.message)
          }
        })
      }
    } else {
      console.log('error submit!!')
      return false
    }
  })
}

</script>

<style lang="scss" scoped>
.addCoupon {
  background: #ffffff;
  .dialog-footer {
    display: flex;
    justify-content: center;
  }
  .formBox {
    margin-top: 20px;
    .el-input {
      width: 240px;
    }
    .item-rule {
      .el-input-number {
        width: 150px;
      }
      dl {
        width: 100%;
        dd {
          margin-left: 0;
          .el-input {
            width: 100px;
          }
        }
      }
    }
  }
  .selectBtn {
    width: 100px;
    height: 30px;
    line-height: 30px;
    background: #66b1ff;
    color: #ffffff;
    text-align: center;
    display: inline-block;
    font-size: 14px;
    margin: 10px auto;
    border-radius: 4px;
    cursor: pointer;
    position: relative;
    i {
      position: absolute;
      right: -10px;
      top: -10px;
      width: 25px;
      height: 25px;
      line-height: 25px;
      background: #ffffff;
      border-radius: 50%;
      border: 1px solid #66b1ff;
      text-align: center;
      color: #3A68F2;
      font-style: normal;
      font-size: 12px;
    }
  }
  .footBtnBox {
    width: 100%;
    display: flex;
    justify-content: center;
    margin-top: 50px;
  }
}
</style>
